
class JsBridge {
    constructor() {
        this.taskId = 1;
        this._callbacks = $.Callbacks();

        if (! window.localStorage) {
            // alert("window.localStorage");
            // window.localStorage = {
            //     getItem: (k) => {
            //         this.sendRequest("localStorage.getItem", {key: k}).then(result => {

            //         });
            //     },

            //     setItem: (k, v) => {
            //         this.sendRequest("localStorage.setItem", { key: k, value: v }).then(result => {

            //         });
            //     }
            // };
        } else {
            // alert("localstorage is ok");
        }

        let timer = setInterval(() => {
            if (this._check()) {
                clearInterval(timer);
                
                __jsbridge["notify"] = (data) => {
                    this._callbacks.fireWith(this, [data]);
                };

                this.sendRequest("user.config", {
                    baseUrl: API.baseUrl
                });
            }
        }, 200);
    }

    getConfig(loginId) {
        let deferred = $.Deferred(), timer = setInterval(() => {
            if (this._check()) {
                this.sendRequest("config.get", {LoginID: loginId}).then(resp => {
                    deferred.resolve(resp.data);
                })
                clearInterval(timer);
            }
        }, 200);

        return deferred;
    }

    on(cb) {
        this._callbacks.add(cb);
    } 

    _check() {
        return typeof (__jsbridge) !== 'undefined' && typeof(__jsbridge) !== undefined;
    }

    sendRequest(type, data) {
        let deferred = $.Deferred();

        if (this._check()) {
            data = data || {};
            let taskId = this.taskId++, obj = { taskId: taskId, type: type, data: data };

            $.get('http://jsbridge?task=' + encodeURIComponent(JSON.stringify(obj)));

            let timer = setInterval(() => {
                if (__jsbridge[taskId]) {
                    let result = __jsbridge[taskId];
                    __jsbridge[taskId] = undefined;
                    clearInterval(timer);

                    deferred.resolve(result);
                }
            }, 200);
        } else {
            deferred.reject();
        }     

        return deferred;
    }
}

export default new JsBridge();